// pages/message/index/index.js
var Zan = require('../../../dist/index');
var app = getApp()
var requestUrl = app.globalData.requestUrl;
const Util = require('../../../utils/util.js');
var total = 10;
var count = 10;
var pageindex = 0;


Page(Object.assign({}, Zan.Dialog, {
	/**
   * 页面的初始数据
   */
	data: {
		sysMsg: [],
		loading: false,
		nodata: false, // 暂无数据
		nodata_str: '暂无消息',
		nomore: false, // 没有更多数据
		startX: 0, //开始坐标
		startY: 0,
		pageSize: 10,
		pageNum: 1
	},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // var text = wx.getStorageSync();
    // console.log(text);
    var that = this;
    
  },
  getMsg: function() {
		//console.log("查询")
		var that = this;
		// var account = wx.getStorageSync('phone');
		// var sibrccode = wx.getStorageSync('sibrccode');
		
		try {
			var newDate = wx.getStorageSync("newDate");
			var newTime = wx.getStorageSync("newTime");
			if (!newDate) {
				// Do something with return value
				newDate = "0000-00-00";
			}
			if (!newTime) {
				// Do something with return value
				newTime = "00:00:00";
			}
			wx.request({
				url: requestUrl + 'mui/affiche',
				method: 'GET',
				dataType: 'json',
				data: {
					date: newDate,
					time: newTime
				},
				header: {
					'content-type': 'application/json'
				},
				success: function (res) {
					var data = res.data;
					wx.stopPullDownRefresh();
					console.log(data)
					if (data.length != 0) {
						that.setMessage(data);
					} else {
						that.showMsg();
					}
				},
				fail: function () {
					wx.stopPullDownRefresh();
					that.showMsg();
				}
			})
		} catch (e) {
			// Do something when catch error
			wx.stopPullDownRefresh();
		}
    
  },
  setMessage:function(data) {
		var sysMsg = wx.getStorageSync('sysMsg') || []; // 获取已有消息
		console.log("setMessage: " + sysMsg.length)
    var newDate = data[0].createdate;
    var newTime = data[0].createtime;
    wx.setStorageSync("newDate", newDate);
    wx.setStorageSync("newTime", newTime);

		var nday = Util.getDate(0); // 今天
		var yday = Util.getDate(-1); // 昨天
		var bday = Util.getDate(-2); // 前天
		for (let i = data.length - 1; i >= 0; i-- ) {
			var timeStr = "";
			var time = data[i].createtime;
			var date = data[i].createdate;
			if (date == nday) { // 今天
				timeStr = time.substr(0, 5);
			} else if (date == yday) { // 昨天
				timeStr = "昨天 " + time.substr(0, 5);
			} else if (date == bday) { //前天
				timeStr = "前天 " + time.substr(0, 5);
			} else { // 显示日期
				timeStr = date.substr(5, 5);
			}
			var content = Util.replaceStr(data[i].content);
      var msg = {
        read: false,
        msgType: data[i].type,
        content: data[i].content.replace(/\\n/g, "\n"),
        msgId: data[i].id,
        date: data[i].createdate,
        time: data[i].createtime,
				summary: content.length > 16 ? (content.substr(0, 16) + "...") : content,
				// summary: data[i].content.length > 16 ? (data[i].content.substr(0, 16) + "...") : data[i].content,
				timeStr: timeStr
      };
			// sysMsg.push(msg);
			sysMsg.splice(0, 0, msg);
    }
		console.log(sysMsg)
		// wx.setStorage({
		// 	key: "sysMsg",
		// 	data: sysMsg
		// })
		try {
			wx.setStorageSync('sysMsg', sysMsg)
			this.setData({
				sysMsg: sysMsg,
				nodata: false
			});
			this.showMsg();
		} catch (e) {
		}
		
  },
  showMsg: function () {
		console.log("showMsg")
    
		try {
			var sysMsg = wx.getStorageSync('sysMsg') || [];
			console.log("sysMsg: "+ sysMsg)
			var pageSize = this.data.pageSize;
			if (sysMsg.length == 0) {
				this.setData({
					sysMsg: sysMsg,
					nodata: true
				});
			} else if (sysMsg.length <= pageSize) {
				this.setData({
					sysMsg: sysMsg,
					nomore: true
				});
			} else if (sysMsg.length > pageSize) {
				this.setData({
					sysMsg: sysMsg.slice(0, pageSize)
				});
			}
		} catch (e) {
			// Do something when catch error
		}
		
	},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady: function () {
		this.getMsg();
		// wx.startPullDownRefresh();
	},

  /**
   * 生命周期函数--监听页面显示
   */
	onShow: function () {

	},
  // bindDel: function (msgid) {
  //   var that = this;
    
  // },
  msgDetail: function (event) {
		var that = this;
    var msgid = event.currentTarget.dataset.id;
		var index = event.currentTarget.dataset.index;
		try {
			var sysMsg = wx.getStorageSync('sysMsg') || [];
			//console.log(sysMsg)
			if (sysMsg) {
				var message = sysMsg.splice(index, 1)[0];
				//console.log(message);
				message.read = true;
				sysMsg.splice(index, 0, message);
				// 重新渲染
				that.setData({
					sysMsg: sysMsg
				});
				// 更改本地存储
				wx.setStorage({
					key: "sysMsg",
					data: sysMsg
				})
			}
		} catch (e) {
			// Do something when catch error
		}
		wx.navigateTo({
			url: '/pages/message/msgDetail/msgDetail?id=' + msgid
		})
  },
	remove: function (event) {
		var that = this;
		var index = event.currentTarget.dataset.index;
		wx.showModal({
			title: '提示',
			content: '是否删除此消息？',
			success: function (res) {
				if (res.confirm) {
					try {
						var sysMsg = wx.getStorageSync('sysMsg') || [];
						//console.log(sysMsg)
						if (sysMsg) {
							sysMsg.splice(index, 1); // 删除本地这条记录
							// 重新渲染
							that.setData({
								sysMsg: sysMsg
							});
							// 更改本地存储
							wx.setStorage({
								key: "sysMsg",
								data: sysMsg
							})
						}
					} catch (e) {
						// Do something when catch error
					}
				}
			}
		})
	},
	//手指触摸动作开始 记录起点X坐标
	touchstart: function (e) {
		console.log(e)
		//开始触摸时 重置所有删除
		var items = this.data.sysMsg;
		items.forEach(function (v, i) {
			// if (v.isTouchMove)//只操作为true的
				v.isTouchMove = false;
		})
		this.setData({
			startX: e.touches[0].clientX,
			startY: e.touches[0].clientY,
			sysMsg: items
		})
	},
	//滑动事件处理
	touchmove: function (e) {
		var that = this,
			index = e.currentTarget.dataset.index,//当前索引
			startX = that.data.startX,//开始X坐标
			startY = that.data.startY,//开始Y坐标
			touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
			touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
			//获取滑动角度
			angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
			var items = this.data.sysMsg;
			items.forEach(function (v, i) {
				v.isTouchMove = false
				//滑动超过30度角 return
				if (Math.abs(angle) > 30) {
					return;
				}
				if (i == index) {
					if (touchMoveX  > startX) {//右滑
						v.isTouchMove = false
					} else {  //左滑
						if (startX - touchMoveX > 5) {
							v.isTouchMove = true
						}
						
					}
						
				}
			})
			//更新数据
			that.setData({
				sysMsg: items
			})
	},
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
	angle: function (start, end) {
		var _X = end.X - start.X,
			_Y = end.Y - start.Y
		//返回角度 /Math.atan()返回数字的反正切值
		return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
	},
  /**
   * 生命周期函数--监听页面隐藏
   */
	onHide: function () {

	},

  /**
   * 生命周期函数--监听页面卸载
   */
	onUnload: function () {

	},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh: function () {
		this.getMsg();
	},

  /**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom: function () {
    var that = this;
		var pageSize = this.data.pageSize;
		var pageNum = this.data.pageNum + 1;
		console.log("pageNum: "+ pageNum)
		var sysMsg = wx.getStorageSync('sysMsg') || [];
		var maxPageNum = Math.ceil(sysMsg.length/pageSize); // 最大页数
		console.log("maxPageNum: " + maxPageNum)
		console.log("pageNum: " + pageNum)
		
		if (pageNum < maxPageNum) {
			this.setData({
				loading: true
			});
			console.log("11111: " + pageNum)
			setTimeout( () => {
				that.setData({
					sysMsg: sysMsg.slice(0, pageNum * pageSize),
					pageNum: pageNum,
					loading: false
				});
			},1000);
			
		} else if (pageNum == maxPageNum) {
			this.setData({
				loading: true
			});
			setTimeout(() => {
				that.setData({
					sysMsg: sysMsg.slice(0, sysMsg.length),
					pageNum: pageNum,
					nomore: true,
					loading: false
				});
				console.log("当前: " + sysMsg.length + "条")
			}, 1000);
			
		} else {
			console.log("return false")
			return false;
		}
		
	},

  /**
   * 用户点击右上角分享
   */
	onShareAppMessage: function () {
		return {
			path: '/pages/sys/login/login',
			success: function (res) {
				// 转发成功
			},
			fail: function (res) {
				// 转发失败
			}
		}
	}
}))